package com.zcaxer.roomwordsample.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.zcaxer.roomwordsample.workers.SeedDatabaseWorker
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Database(entities = [Word::class, Building::class, BuildingUpgradeInfo::class], version = 1)
abstract class AppRoomDatabase : RoomDatabase() {
    abstract fun wordDao(): WordDao
    abstract fun buildingDao(): BuildingDao
    abstract fun buildingUpgradeInfoDao(): BuildingUpgradeInfoDao

    companion object {
        @Volatile
        private var INSTANCE: AppRoomDatabase? = null

        fun getDatabase(context: Context): AppRoomDatabase {

            return INSTANCE ?: synchronized(this) {
                val instance =
                    Room.databaseBuilder(context.applicationContext, AppRoomDatabase::class.java, "app-database")
                        .addCallback(WordDatabaseCallback(context)).build()
                INSTANCE = instance
                instance
            }
        }
    }

    private class WordDatabaseCallback(val context: Context) : RoomDatabase.Callback() {

        override fun onOpen(db: SupportSQLiteDatabase) {
            super.onOpen(db)
            INSTANCE?.let { database ->
                CoroutineScope(Dispatchers.IO).launch {
                    populateDatabase(database.wordDao())

                }
            }
        }


        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)
            INSTANCE?.let {
                val request = OneTimeWorkRequest.from(SeedDatabaseWorker::class.java)
                WorkManager.getInstance(context).enqueue(request)
            }
        }

        suspend fun populateDatabase(wordDao: WordDao) {
            wordDao.deleteAll()

            var word = Word("Hello")
            wordDao.insert(word)
            word = Word("World!")
            wordDao.insert(word)
        }
    }


}

